package core.genetic.selection;

import java.util.Arrays;

import utility.Pair;
import utility.Utils;
import core.Mode;
import core.genetic.Individual;
import core.genetic.Population;

public class RandomSelection implements Selection{

	final double keeprate;	//procenat roditelja koji prezivljava i pari se
	
	public RandomSelection(double keeprate) {
		this.keeprate = keeprate;
	}
	
	public void select(Population pop, double[] values) {
		int length = values.length;
		Pair<Individual, Double>[] par = (Pair<Individual, Double>[])new Pair<?,?>[values.length];
		for (int i=0; i<values.length; i++){
			par[i] = new Pair<Individual, Double>(pop.get(i), values[i]);
		}
		Arrays.sort(par, new Pair.SecondDescendingComparator<Individual, Double>());
		
		int parent = (int) (keeprate*length);
		for (int i=parent; i<length; i++){	
			int cale = Utils.random.nextInt(parent);
			int keva = Utils.random.nextInt(parent);
			for(int j = 0;cale==keva && j<10;j++)
				keva = Utils.random.nextInt(parent);
			Individual ind = Mode.mode.crossover.crossover(par[cale].first(), par[keva].first());
			par[i].first(ind);
		}
		
		pop.setFirst(par, length);
		
		for(int i = (int)(0.5+Mode.mode.elitismRate*pop.size());i<pop.size();i++) 				
			Mode.mode.mutation.mutate(pop.get(i));

	}

}
